import 'package:amway_superapp_creator_plugin/dialog/edit_phone_dialog.dart';
import 'package:amway_superapp_creator_plugin/models/create_user_info_model.dart';
import 'package:amway_superapp_creator_plugin/models/my_circle_bean.dart';
import 'package:amway_superapp_creator_plugin/net/dio_log_interceptor.dart';
import 'package:amway_superapp_creator_plugin/net/http_manager.dart';
import 'package:amway_superapp_creator_plugin/utils/log_util.dart';
import 'package:amway_superapp_creator_plugin/utils/sp_util.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_flavor/flutter_flavor.dart';
import 'package:uuid/uuid.dart';

import '../../api.dart';
import '../base_model.dart';
import 'official_circle_data.dart';

class MyCircleModel extends BaseModel {
  MyCircleModel({@required Api api}) : super(api: api);
  bool _isChecked = true;

  bool get isChecked => _isChecked;

  checked(bool check) {
    this._isChecked = check;
    notifyListeners();
  }

  List<MyCircleBean> myCircleBean = new List();

  List<MyCircleBean> officialList = [];
  MyCircleData myCircleData = MyCircleData();

  void setChecked(bool checked) {
    this._isChecked = checked;
    if (checked) {
      filterOfficial();
    } else {
      officialList.clear();
      myCircleBean.forEach((element) {
        if (element.officialFlag == "NO") {
          officialList.add(element);
        }
      });
    }
    notifyListeners();
  }

/*
* 圈子列表
* */
  int pageSize = 100;

  void getCircleList(String ada, String amwayId, var identityMarks,
      {int page = 1, bool isChecked = false}) {
    HttpManager().get(
        url: "apis/v1/creator/circles/pageList/$ada/$pageSize/$page/",
        tag: null,
        successCallback: (data) {
          if (data != null) {
            myCircleData = MyCircleData.fromJson(data);
            if (page == 1) {
              myCircleBean.clear();
              myCircleBean = myCircleData.content;
              queryfficial(amwayId, identityMarks, back: (result) {
                setChecked(isChecked == null ? false : isChecked);
              });
            } else {
              myCircleBean.addAll(myCircleData.content);
              notifyListeners();
            }
          }
        },
        errorCallback: (data) {});
  }

  /*
  * 删除圈子
  * */
  void deleteCircle(String id, int position, {BoolStringCallBack back}) {
    HttpManager().put(
        url: "apis/v1/creator/circles/${id}/remove/",
        tag: null,
        successCallback: (data) {
          if (data != null) {
            myCircleBean.removeAt(position);
            back.call(true, "");
          }
        },
        errorCallback: (data) {
          back.call(false, data.message);
        });
  }

  /*
  * 撤销
  * */
  void revoke(String id, int position, {BoolStringCallBack back}) {
    HttpManager().put(
        url: "apis/v1/creator/circles/$id/un_publish/",
        tag: null,
        successCallback: (data) {
          if (data != null) {
            myCircleBean[position].auditStatus = "PASSED";
            myCircleBean[position].publishStatus = "UN_PUBLISH";
            notifyListeners();
            back.call(true, "");
          }
        },
        errorCallback: (data) {
          back.call(false, data.message);
        });
  }

  void upModuleOffShow(String ada) {
    HttpManager().post(
        url:
            "apis/v1/creator/module-configs/upModuleOffiShow/$ada/${isChecked ? "ON" : "OFF"}/CIRCLE/",
        tag: null,
        successCallback: (data) {
          SpUtil.setData(
              "${SpUtil.official_circle}$ada", isChecked ? "ON" : "OFF");
        },
        errorCallback: (data) {});
  }

  List<MyCircleBean> filterOfficial() {
    myCircleBean
        .sort((left, right) => right.officialFlag.compareTo(left.officialFlag));
    return myCircleBean;
  }


  void queryfficial(String amwayId, var identityMarks,
      {StringCallBack back}) async {
    try {
      var queryParameters = {
        //"q": "安利头条",
        "start": 0,
        "rows": 3,
        //"tags": identityMarks,
        "sort": "-views"
      };
      var uuid = Uuid();
      var v1 = uuid.v1();
      var heards = {
        "Authorization": FlavorConfig.instance.variables["AppCode"],
        "X-Ca-Nonce": v1,
      };
      var amwayBaseUrl = FlavorConfig.instance.variables["amwayBaseUrl"];
      Options options = Options(headers: heards);
      BaseOptions opt = BaseOptions(
        connectTimeout: 1000 * 60,
        receiveTimeout: 1000 * 60,
      );
      
      Dio dio = Dio(opt);
      dio.interceptors.add(DioLogInterceptor());
      Response response = await dio.get(amwayBaseUrl + "/creators/articles",
          queryParameters: queryParameters, options: options);
      LogUtil.e(response.data);
      LogUtil.e(response.headers);

      if (response.statusCode == 200) {
        response.data.forEach((element) {
          var official = OfficialCircleData.fromJson(element);
          var list = List<ImagesBean>();
          var officialIds = List<String>();
          official.products.forEach((element) {
            officialIds..add(element.id);
          });
          official.images.forEach((element) {
            list.add(ImagesBean(
                data: element,
                dataType: "IMAGE"));
          });

          myCircleBean.insert(
              0,
              MyCircleBean(
                  officialFlag: "YES",
                  medias: list,
                  publishDate: official.publishDate,
                  officialId: officialIds,
                  content: official.content,
                  publishStatus: "PUBLISHED",
                  title: official.title,
                  id: official.url));
        });
        back.call("success");
      } else {
        back.call("error");
      }
    } catch (e) {
      print(e);
      back.call("error");
    }
  }
}
